/*
 * @Description: 
 * @Author: handongliang dongliang.han@12301.cn
 * @Date: 2023-05-12 09:19:39
 * @LastEditTime: 2023-06-09 16:48:09
 */
import axios from 'axios';
import { clearAuthInfo, getToken } from '@/utils/authority';
import { message } from "@/theme/EscapeAntd.tsx";

const request = axios.create({
  baseURL: __API_BASE_URL__,
  timeout: 30 * 1000,
  withCredentials: true,
})

request.interceptors.request.use((config: any) => {
  const token = getToken();
  if (!config.url.startsWith('https://guangxi-video.tourage.cn')) {
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
  }
  if (config.url.startsWith('http')) {
    config.baseURL = ''; // 将baseURL设为空字符串，避免添加到请求URL中
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

request.interceptors.response.use((response) => {
  if (response.request.responseType === 'blob') {
    return Promise.resolve(response);
  }
  const result = response.data
  if (result?.code === 200) {
    return Promise.resolve(result.data)
  }
  if (result?.code === 403) {
    clearAuthInfo();
    window.location.href = import.meta.env.BASE_URL + 'login'
    message.error('未登录或登录已过期，请重新登录。');
    return Promise.reject(result)
  }
  if (window.location.pathname === "/login") {
    message.error(result.message);
  }
  return Promise.reject(result)
}, (error) => {
  if (error.response.status === 403) {
    clearAuthInfo();
    window.location.href = import.meta.env.BASE_URL + 'login'
    message.error('未登录或登录已过期，请重新登录。');
    return Promise.reject(error)
  }
  return Promise.reject(error);
});


export default request
